<!-- 数据目录导航器 - 系统管理模块 -->
<template>
  <div class="data-navigator">
    <!-- 顶部工具栏 -->
    <div class="navigator-header">
      <div class="header-left">
        <h1 class="navigator-title">
          <el-icon class="title-icon"><FolderOpened /></el-icon>
          数据目录导航器
        </h1>
        <div class="data-info">
          <el-tag type="info" size="small">{{ dataStats.totalFiles }} 个文件</el-tag>
          <el-tag type="success" size="small">{{ dataStats.totalSize }}</el-tag>
        </div>
      </div>

      <div class="header-actions">
        <el-button-group class="action-group">
          <el-button size="small" @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新目录
          </el-button>
          <el-button size="small" @click="exportData">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
          <el-button size="small" type="primary" @click="openAnalysis">
            <el-icon><DataAnalysis /></el-icon>
            数据分析
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 主工作区域 -->
    <div class="navigator-content">
      <!-- 左侧层级浏览器 -->
      <el-aside :width="leftPanelWidth" class="left-panel">
        <HierarchyBrowser 
          :treeData="hierarchyData"
          @nodeSelect="handleNodeSelect"
          @nodeExpand="handleNodeExpand"
        />
        
        <!-- 面板调整器 -->
        <div
          class="panel-resizer left-resizer"
          @mousedown="startResize('left', $event)"
        ></div>
      </el-aside>

      <!-- 中央数据可视化区域 -->
      <el-main class="visualization-area">
        <DataVisualization
          ref="dataVisualizationRef"
          :selectedNode="selectedNode"
          :visualizationType="currentVisualization"
          @visualizationChange="handleVisualizationChange"
        />
      </el-main>

      <!-- 右侧元数据检索器 -->
      <el-aside :width="rightPanelWidth" class="right-panel">
        <MetadataRetriever
          :selectedData="selectedNodeData"
          :searchFilters="searchFilters"
          @filterChange="handleFilterChange"
          @dataLocate="handleDataLocate"
        />

        <!-- 面板调整器 -->
        <div
          class="panel-resizer right-resizer"
          @mousedown="startResize('right', $event)"
        ></div>
      </el-aside>
    </div>

    <!-- 底部状态栏 -->
    <div class="navigator-footer">
      <div class="status-left">
        <div class="status-item">
          <el-icon><Files /></el-icon>
          <span>当前选中: {{ selectedNode?.name || '无' }}</span>
        </div>
        <div class="status-item">
          <el-icon><Clock /></el-icon>
          <span>最后更新: {{ formatTime(lastUpdateTime) }}</span>
        </div>
      </div>

      <div class="status-right">
        <div class="visualization-controls">
          <el-button-group size="small">
            <el-button 
              :type="currentVisualization === 'tree' ? 'primary' : ''"
              @click="switchVisualization('tree')"
            >
              <el-icon><Share /></el-icon>
              树形图
            </el-button>
            <el-button 
              :type="currentVisualization === 'map' ? 'primary' : ''"
              @click="switchVisualization('map')"
            >
              <el-icon><Location /></el-icon>
              地图
            </el-button>
            <el-button 
              :type="currentVisualization === 'chart' ? 'primary' : ''"
              @click="switchVisualization('chart')"
            >
              <el-icon><TrendCharts /></el-icon>
              图表
            </el-button>
          </el-button-group>
        </div>
        <div class="performance-indicator">
          <el-icon class="perf-icon" :class="{ active: performanceGood }"><Connection /></el-icon>
          <span class="perf-text">{{ performanceText }}</span>
        </div>
      </div>
    </div>

    <!-- 数据搜索快捷面板 -->
    <transition name="fade">
      <div v-if="showSearchPanel" class="search-panel">
        <div class="search-title">快速搜索</div>
        <div class="search-content">
          <el-input
            v-model="quickSearchText"
            placeholder="输入关键词搜索数据..."
            @input="handleQuickSearch"
            clearable
          >
            <template #prepend>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <div class="search-results" v-if="quickSearchResults.length > 0">
            <div
              v-for="result in quickSearchResults"
              :key="result.id"
              class="search-result-item"
              @click="selectSearchResult(result)"
            >
              <el-icon><Document /></el-icon>
              <span>{{ result.name }}</span>
              <el-tag size="small">{{ result.type }}</el-tag>
            </div>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import {
  FolderOpened,
  Refresh,
  Download,
  DataAnalysis,
  Files,
  Clock,
  Share,
  Location,
  TrendCharts,
  Connection,
  Search,
  Document
} from '@element-plus/icons-vue'

// 导入子组件
import HierarchyBrowser from './components/data-navigator/HierarchyBrowser.vue'
import DataVisualization from './components/data-navigator/DataVisualization.vue'
import MetadataRetriever from './components/data-navigator/MetadataRetriever.vue'

// 组件引用
const dataVisualizationRef = ref(null)

// 面板尺寸
const leftPanelWidth = ref('35vw')
const rightPanelWidth = ref('30vw')

// 数据状态
const dataStats = reactive({
  totalFiles: 1247,
  totalSize: '2.3GB'
})

const selectedNode = ref(null)
const selectedNodeData = ref(null)
const currentVisualization = ref('tree')
const lastUpdateTime = ref(new Date())
const performanceGood = ref(true)

// 搜索相关
const showSearchPanel = ref(false)
const quickSearchText = ref('')
const quickSearchResults = ref([])
const searchFilters = reactive({
  device: '',
  timeRange: [],
  location: ''
})

// 层级数据
const hierarchyData = ref([
  {
    id: 'signals',
    name: '信号级数据',
    type: 'folder',
    children: [
      {
        id: 'radar-signals',
        name: '雷达信号',
        type: 'signal',
        count: 156,
        children: [
          { id: 'radar-1', name: 'S波段雷达', type: 'device', location: '北京', lastUpdate: '2024-01-15' },
          { id: 'radar-2', name: 'X波段雷达', type: 'device', location: '上海', lastUpdate: '2024-01-14' }
        ]
      },
      {
        id: 'comm-signals',
        name: '通信信号',
        type: 'signal',
        count: 89,
        children: [
          { id: 'comm-1', name: 'UHF通信', type: 'device', location: '广州', lastUpdate: '2024-01-13' },
          { id: 'comm-2', name: 'VHF通信', type: 'device', location: '深圳', lastUpdate: '2024-01-12' }
        ]
      }
    ]
  },
  {
    id: 'functions',
    name: '功能级数据',
    type: 'folder',
    children: [
      {
        id: 'analysis-results',
        name: '分析结果',
        type: 'function',
        count: 234,
        children: [
          { id: 'spectrum-analysis', name: '频谱分析', type: 'analysis', size: '1.2GB' },
          { id: 'pattern-recognition', name: '模式识别', type: 'analysis', size: '0.8GB' }
        ]
      },
      {
        id: 'processed-data',
        name: '处理数据',
        type: 'function',
        count: 167,
        children: [
          { id: 'filtered-signals', name: '滤波信号', type: 'processed', size: '0.3GB' }
        ]
      }
    ]
  }
])

// 面板调整大小
let isResizing = false
let resizeType = null
let startX = 0
let startWidth = 0

// 计算属性
const performanceText = computed(() => {
  return performanceGood.value ? '良好' : '一般'
})

// 时间格式化
const formatTime = (time) => {
  if (!time) return '--'
  return time.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 节点选择处理
const handleNodeSelect = (node) => {
  selectedNode.value = node
  selectedNodeData.value = {
    ...node,
    details: {
      path: `/data/${node.type}/${node.id}`,
      permissions: 'read-only',
      metadata: {
        created: new Date(Date.now() - Math.random() * 10000000000),
        modified: new Date(Date.now() - Math.random() * 1000000000),
        size: node.size || `${Math.floor(Math.random() * 1000)}MB`
      }
    }
  }
  ElMessage.success(`已选中: ${node.name}`)
}

// 节点展开处理
const handleNodeExpand = (node) => {
  // 动态加载子节点数据
  console.log('展开节点:', node.name)
}

// 可视化切换
const switchVisualization = (type) => {
  currentVisualization.value = type
  if (dataVisualizationRef.value) {
    dataVisualizationRef.value.switchVisualization(type)
  }
}

const handleVisualizationChange = (type) => {
  currentVisualization.value = type
}

// 过滤器变化处理
const handleFilterChange = (filters) => {
  Object.assign(searchFilters, filters)
  // 根据过滤条件刷新数据
  refreshDataWithFilters()
}

// 数据定位处理
const handleDataLocate = (data) => {
  // 在可视化组件中定位到指定数据
  if (dataVisualizationRef.value) {
    dataVisualizationRef.value.locateData(data)
  }
  ElMessage.success(`已定位到: ${data.name}`)
}

// 顶部工具栏操作
const refreshData = () => {
  lastUpdateTime.value = new Date()
  ElMessage.success('数据目录已刷新')
}

const exportData = () => {
  ElMessage.info('导出功能开发中...')
}

const openAnalysis = () => {
  ElMessage.info('数据分析工具启动中...')
}

// 快速搜索
const handleQuickSearch = (value) => {
  if (!value) {
    quickSearchResults.value = []
    return
  }
  
  // 模拟搜索结果
  quickSearchResults.value = [
    { id: 'search-1', name: `${value} 相关数据 1`, type: '信号' },
    { id: 'search-2', name: `${value} 相关数据 2`, type: '功能' }
  ].filter(item => Math.random() > 0.3)
}

const selectSearchResult = (result) => {
  selectedNode.value = result
  showSearchPanel.value = false
  quickSearchText.value = ''
  quickSearchResults.value = []
}

// 根据过滤条件刷新数据
const refreshDataWithFilters = () => {
  console.log('应用过滤条件:', searchFilters)
  // 这里可以调用API根据过滤条件获取数据
}

// 面板调整大小
const startResize = (type, event) => {
  isResizing = true
  resizeType = type
  startX = event.clientX
  startWidth = type === 'left' ?
    parseInt(leftPanelWidth.value) :
    parseInt(rightPanelWidth.value)

  document.addEventListener('mousemove', handleResize)
  document.addEventListener('mouseup', stopResize)
  document.body.style.cursor = 'col-resize'
}

const handleResize = (event) => {
  if (!isResizing) return

  const deltaX = event.clientX - startX
  const vwUnit = window.innerWidth / 100

  if (resizeType === 'left') {
    const newWidth = Math.max(25, Math.min(45, startWidth + deltaX / vwUnit))
    leftPanelWidth.value = `${newWidth}vw`
  } else if (resizeType === 'right') {
    const newWidth = Math.max(25, Math.min(40, startWidth - deltaX / vwUnit))
    rightPanelWidth.value = `${newWidth}vw`
  }
}

const stopResize = () => {
  isResizing = false
  resizeType = null
  document.removeEventListener('mousemove', handleResize)
  document.removeEventListener('mouseup', stopResize)
  document.body.style.cursor = 'default'
}

// 键盘快捷键
const handleKeydown = (event) => {
  if (event.ctrlKey && event.key === 'f') {
    event.preventDefault()
    showSearchPanel.value = !showSearchPanel.value
  } else if (event.key === 'Escape') {
    showSearchPanel.value = false
  }
}

// 生命周期
onMounted(() => {
  document.addEventListener('keydown', handleKeydown)
  
  // 模拟性能监控
  setInterval(() => {
    performanceGood.value = Math.random() > 0.2
  }, 5000)
})

onBeforeUnmount(() => {
  document.removeEventListener('keydown', handleKeydown)
  document.removeEventListener('mousemove', handleResize)
  document.removeEventListener('mouseup', stopResize)
})
</script>

<style scoped>
/* 适配侧边栏布局的样式 */
* {
  box-sizing: border-box;
}

/* 主容器 - 适配侧边栏布局 */
.data-navigator {
  width: 96vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #1f2d3d;
  overflow: hidden;
  position: absolute;
  top: 0;
  left: 4vw;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 顶部工具栏 */
.navigator-header {
  height: 7vh;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 2vw;
  background: linear-gradient(135deg, #263445, #1f2d3d);
  border-bottom: 1px solid #2d3a4b;
  box-shadow: 0 0.2vh 0.8vh rgba(0, 0, 0, 0.3);
  z-index: 100;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 2vw;
}

.navigator-title {
  margin: 0;
  font-size: 1.4rem;
  font-weight: 600;
  color: #bfcbd9;
  display: flex;
  align-items: center;
  gap: 1vw;
}

.title-icon {
  font-size: 1.6rem;
  color: var(--el-color-primary);
}

.data-info {
  display: flex;
  align-items: center;
  gap: 0.8vw;
}

.header-actions {
  display: flex;
  gap: 1vw;
}

.action-group .el-button {
  height: 3.5vh;
  font-size: 0.85rem;
}

/* 主工作区域 */
.navigator-content {
  flex: 1;
  display: flex;
  overflow: hidden;
  min-height: 0;
}

/* 左侧面板 */
.left-panel {
  background: #263445;
  border-right: 1px solid #2d3a4b;
  position: relative;
  min-width: 25vw;
  max-width: 45vw;
  flex-shrink: 0;
}

/* 右侧面板 */
.right-panel {
  background: #263445;
  border-left: 1px solid #2d3a4b;
  position: relative;
  min-width: 25vw;
  max-width: 40vw;
  flex-shrink: 0;
}

/* 面板调整器 */
.panel-resizer {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 0.4vw;
  background: transparent;
  cursor: col-resize;
  z-index: 10;
  transition: background-color 0.2s ease;
}

.left-resizer {
  right: -0.2vw;
}

.right-resizer {
  left: -0.2vw;
}

.panel-resizer:hover {
  background: #409EFF;
}

/* 中央可视化区域 */
.visualization-area {
  flex: 1;
  padding: 0;
  background: #0a0f1b;
  position: relative;
  overflow: hidden;
}

/* 底部状态栏 */
.navigator-footer {
  height: 5vh;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 2vw;
  background: #1f2d3d;
  border-top: 1px solid #2d3a4b;
  font-size: 0.8rem;
}

.status-left, .status-right {
  display: flex;
  align-items: center;
  gap: 2vw;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 0.5vw;
  color: #bfcbd9;
}

.visualization-controls {
  display: flex;
  align-items: center;
}

.visualization-controls .el-button {
  height: 2.5vh;
  font-size: 0.7rem;
}

.performance-indicator {
  display: flex;
  align-items: center;
  gap: 0.5vw;
}

.perf-icon {
  font-size: 0.9rem;
  color: var(--el-color-warning);
  transition: color 0.3s ease;
}

.perf-icon.active {
  color: var(--el-color-success);
}

.perf-text {
  font-size: 0.8rem;
  color: #bfcbd9;
}

/* 搜索面板 */
.search-panel {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #263445;
  border: 1px solid #2d3a4b;
  border-radius: 1vh;
  padding: 2vh;
  box-shadow: 0 1vh 3vh rgba(0, 0, 0, 0.5);
  z-index: 2000;
  min-width: 40vw;
  max-height: 60vh;
  overflow-y: auto;
}

.search-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #bfcbd9;
  margin-bottom: 1.5vh;
  text-align: center;
}

.search-content {
  display: flex;
  flex-direction: column;
  gap: 1vh;
}

.search-results {
  max-height: 40vh;
  overflow-y: auto;
  border: 1px solid #2d3a4b;
  border-radius: 0.5vh;
  background: #1f2d3d;
}

.search-result-item {
  display: flex;
  align-items: center;
  gap: 1vw;
  padding: 1vh 1.5vw;
  cursor: pointer;
  color: #bfcbd9;
  border-bottom: 1px solid #2d3a4b;
  transition: background-color 0.2s ease;
}

.search-result-item:hover {
  background: #2d3a4b;
}

.search-result-item:last-child {
  border-bottom: none;
}

/* 过渡动画 */
.fade-enter-active, .fade-leave-active {
  transition: all 0.3s ease;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
  transform: translate(-50%, -50%) scale(0.9);
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .left-panel {
    min-width: 28vw;
    max-width: 42vw;
  }
  
  .right-panel {
    min-width: 28vw;
    max-width: 38vw;
  }
}

@media (max-width: 1200px) {
  .navigator-title {
    font-size: 1.2rem;
  }

  .data-info {
    display: none;
  }
  
  .left-panel {
    min-width: 30vw;
    max-width: 40vw;
  }
  
  .right-panel {
    min-width: 30vw;
    max-width: 35vw;
  }
}

/* Element Plus 组件深色主题覆盖 */
.data-navigator :deep(.el-button) {
  background: #263445 !important;
  border-color: #2d3a4b !important;
  color: #bfcbd9 !important;
}

.data-navigator :deep(.el-button:hover) {
  background: #2d3a4b !important;
  border-color: #409EFF !important;
  color: #409EFF !important;
}

.data-navigator :deep(.el-button--primary) {
  background: #409EFF !important;
  border-color: #409EFF !important;
  color: #ffffff !important;
}

.data-navigator :deep(.el-button--primary:hover) {
  background: #66B2FF !important;
  border-color: #66B2FF !important;
}

.data-navigator :deep(.el-tag) {
  background: #263445 !important;
  border-color: #2d3a4b !important;
  color: #bfcbd9 !important;
}

.data-navigator :deep(.el-tag--success) {
  background: #1f4838 !important;
  border-color: #2d5a41 !important;
  color: #67C23A !important;
}

.data-navigator :deep(.el-tag--info) {
  background: #1f2d3d !important;
  border-color: #2d3a4b !important;
  color: #909399 !important;
}

.data-navigator :deep(.el-input) {
  background: #263445 !important;
}

.data-navigator :deep(.el-input__wrapper) {
  background: #263445 !important;
  border-color: #2d3a4b !important;
  box-shadow: 0 0 0 1px #2d3a4b inset !important;
}

.data-navigator :deep(.el-input__inner) {
  background: #263445 !important;
  color: #bfcbd9 !important;
}

.data-navigator :deep(.el-input__inner::placeholder) {
  color: #8591a3 !important;
}

.data-navigator :deep(.el-button-group .el-button) {
  background: #263445 !important;
  border-color: #2d3a4b !important;
  color: #bfcbd9 !important;
}

.data-navigator :deep(.el-button-group .el-button:hover) {
  background: #2d3a4b !important;
  border-color: #409EFF !important;
  color: #409EFF !important;
}
</style>